package com.zxf.appliction.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zxf.appliction.domain.Filesup;
import com.zxf.appliction.domain.Params;
import com.zxf.appliction.domain.Staffvo;
import com.zxf.appliction.service.FileService;
import com.zxf.appliction.util.DateJsonValueProcessor;


@Controller 
@RequestMapping("filesup")
public class FileContorller {
	@Autowired
	private FileService fileService;
	
	
	private static Logger logger = Logger.getLogger(FileContorller.class);
	
	/**
	 * 文件上传
	 * @param staffVo 
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(value = "/photoUpload.do", method = RequestMethod.POST)
	public JSONObject addFileUp(Staffvo staffVo, HttpServletResponse response, HttpServletRequest request){
		Filesup fileUp = new Filesup();
		JSONObject obj = new JSONObject();
		// 获取用户
		// Admin admin = (Admin) request.getSession().getAttribute("admin");
		
		
		int userid = 1;// 用户ID
		Date createdTime = new Date();
		//MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
		// 使用MultipartHttpServletRequest包装文件数据
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 目录命名格式如：*files2013-03-05-22
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		dateformat.format(createdTime);
		// 构建图片保存的目录
		String foldername = "file" + dateformat.format(new Date());
		String logoPathDir = "E:/upload/" + foldername;
		// 得到图片保存目录的真实路径
		// request.getSession().getServletContext().getRealPath(logoPathDir);
		// 根据真实路径创建目录
		File logoSaveFile = new File(logoPathDir);
		if (!logoSaveFile.exists())
			logoSaveFile.mkdirs();
		// 页面控件的文件流
		MultipartFile multipartFile = multipartRequest.getFile("avatar");
		if (null == multipartFile || multipartFile.isEmpty()) {
			multipartFile = multipartRequest.getFile("imgFile");
		}
		if (null == multipartFile || multipartFile.isEmpty()) {
			Iterator<String> filedFileNames = multipartRequest.getFileNames();
			String filedName ="";
			while (filedFileNames.hasNext()) {
				filedName = filedFileNames.next(); // 文件文本框的名称
				// 获取该文件框中上传的文件，即对应到上传到服务器中的文件
			}
			 multipartFile = multipartRequest.getFile(filedName);
		}
		
		
		// 获取文件名/
		String filename = multipartFile.getOriginalFilename();
		float filesize = multipartFile.getSize();
		// double filesize3= filesize
		float filesize2 = (filesize / 1024);
		String strfilesize = String.valueOf((float)(Math.round(filesize2*100))/100) + "KB";
		String filetype = multipartFile.getContentType();
		String filesrc = "http://127.0.0.1:8081/dpslogs/" + foldername + "/" + filename;
		
		fileUp.setFilesize(strfilesize);
		fileUp.setFiletype(filetype);
		//fileUp.setId(String.valueOf(uuid));
		fileUp.setFilename(filename);
		fileUp.setPath(logoPathDir);
		fileUp.setUpdata(dateformat.format(createdTime));
		fileUp.setFilesrc(filesrc);

		staffVo.setPublishdate(createdTime);
		String Staffname ="";
		
		try {
			if(null != staffVo.getStaffname() && staffVo.getStaffname() != ""){
				Staffname = URLDecoder.decode(staffVo.getStaffname(), "utf-8");
				
			}
			
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		staffVo.setStaffname(Staffname);
		

		
		// 拼成完整的文件保存路径加文件
		String fileName = logoPathDir + File.separator + filename;
		File file = new File(fileName);
		try {
			// 保存上传文件
			multipartFile.transferTo(file);
			logger.info(filename + "上传成功！！！");
			try {
				//staffid存在就不在往staffvo表里插数据
				Integer staffid = fileService.getStaffidByStaffname(Staffname);
				// 插入数据库
				if(null!=staffid && staffid > 0){
					fileUp.setstaffid(staffid);
					 fileService.insertFile(fileUp);
					 obj.put("success", "true");
					 obj.put("error", 0);
					 obj.put("url", filesrc);
					
				}else{
					int aa = fileService.insertAndGetstaffID(staffVo);
					
					if (aa > 0 ) {
						fileUp.setstaffid(staffVo.getStaffid());
						 fileService.insertFile(fileUp);
						 obj.put("success", "true");
						 obj.put("error", 0);
						 obj.put("url", filesrc);
					}
					
				}
				
				
			} catch (Exception e) {
				// TODO: handle exception
				obj.put("success", "false");
				logger.error("异常出现：" + e);
			}
			
		} catch (IllegalStateException e) {
			obj.put("success", "false");
			logger.error("异常出现：" + e);
		} catch (IOException e) {
			obj.put("success", "false");
			logger.error("异常出现：" + e);
		}
		return obj;

	}

	

	

	

	
	/**
	 * 文件列表
	 * @param params
	 * @param request
	 * @param response
	 * @return list 集合
	 */
	@RequestMapping(value = "/filelist.do", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject filelist(Params params, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();

		
		int start = (params.getPage() - 1) * params.getLimit();
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		// jsonConfig.registerJsonValueProcessor(Date.class, new
		// JsonDateValueProcessor());
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List filelist = fileService.getFilelist(params);
		int totle = fileService.getFiletotle();
		obj.put("data", JSONArray.fromObject(filelist, jsonConfig));
		obj.put("total", totle); // 统计数量，
		obj.put("success", true);

		logger.info("filelist:"+ obj.toString());
		return obj;

	}

	

	

}